package ihm.panel.node;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;

import ihm.applet.KrakenApplet;
import ihm.panel.PanelInterface;
import ihm.panel.camera.CameraPanel;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.hibernate.Session;

import bdd.standalone.bean.Camera;
import bdd.standalone.bean.SiteServer;
import bdd.standalone.bean.User;

import enumTypes.Rank;

//import bdd.external.bean.Camera;
//import bdd.external.bean.SiteServer;

/**
 * Affiche l'arborescence des sites et caméras.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class NodePanel extends JPanel implements PanelInterface, TreeSelectionListener {

	private static final long serialVersionUID = 1L;
	private KrakenApplet applet;
	private CameraPanel camera_jp;

	private JTree tree;
	private DefaultTreeModel treeModel;
	private JScrollPane treeView;
	private DefaultMutableTreeNode top;
	private static String[] OPTION_SITE = {/*"Qualité de service", */"Chiffrement"};
	private static String[] OPTION_CAMERA = {"Flux", "Vidéos", "Tâches"/*, "Stockage"*/};
	
	private SiteServer currentSite;
	private Camera currentCamera;
	
	private boolean buildTree;
	
	/**
	 * Constructeur.
	 * @param applet
	 * @param camera_jp
	 */
	public NodePanel(KrakenApplet applet, CameraPanel camera_jp) {
		this.applet = applet;
		this.camera_jp = camera_jp;
		initPanel();
	}

	@Override
	public void initPanel() {
		this.setLayout(new BorderLayout());
		top = new DefaultMutableTreeNode("Liste des sites");
		treeModel = new DefaultTreeModel(top);
		createNodes();
		tree = new JTree(treeModel);
		tree.setRootVisible(false);
		tree.addTreeSelectionListener(this);

		treeView = new JScrollPane(tree);

		this.buildTree = false;
		
		add(treeView, BorderLayout.CENTER);
	}


	/**
	 * Va chercher les informations dans la base de données et créer l'arbre en fonction.
	 */
	public void createNodes() {
		if(applet.isUserLogged()){
			//System.out.println("Plop");
			top.removeAllChildren();
			
			DefaultMutableTreeNode site = null;
			DefaultMutableTreeNode camera = null;
			DefaultMutableTreeNode option = null;
	
			Session session = applet.getSession();
			User user = (User) session.load(User.class, applet.getUser_ID());
			//List<SiteServer> resultatsSite = session.createCriteria(SiteServer.class).addOrder(Order.asc("siteserv_id")).list();
			
			Set<Camera> resultatsCamera = user.getCameras();//session.createCriteria(Camera.class).list();
			ArrayList<SiteServer> resultatsSite = new ArrayList<SiteServer>();
			
			for(Camera c : resultatsCamera){
				SiteServer siteServer = c.getSite();
				if(!resultatsSite.contains(siteServer))	resultatsSite.add(siteServer);
			}
			
			Collections.sort(resultatsSite, new Comparator<SiteServer>(){
				public int compare(SiteServer site1, SiteServer site2) {
					if(site1.getSiteserv_id() > site2.getSiteserv_id())	return 1;
					else if(site2.getSiteserv_id() > site1.getSiteserv_id())	return -1;
					else	return 0;
				}
			});
			
			//Pour chaque site, on cherche les cameras qui leur appartienne et on les ajoute au node
			for(int i = 0; i < resultatsSite.size(); i++) {
	
				site = new DefaultMutableTreeNode(resultatsSite.get(i));
				treeModel.insertNodeInto(site, top, top.getChildCount());
				
				for(int j = 0; j < OPTION_SITE.length; j++){
					option = new DefaultMutableTreeNode(OPTION_SITE[j]);
					treeModel.insertNodeInto(option, site, site.getChildCount());
					
					if(applet.isUserLogged()){
						if(OPTION_SITE[j].equalsIgnoreCase("Chiffrement")){
							if(!user.getUser_rank().equals(Rank.Administrateur)){
								treeModel.removeNodeFromParent(option);
							}
						}
					}
				}
	
				/*List<Camera> resultatsCamera = session.createCriteria(Camera.class)
						.addOrder(Order.asc("cam_id"))
						.add(Restrictions.eq("site", resultatsSite.get(i)))
						.createCriteria("site")
						.list();*/
	
				for(Camera cam : resultatsCamera){
					if(cam.getSite().equals(resultatsSite.get(i))){
						camera = new DefaultMutableTreeNode(cam);
					
						treeModel.insertNodeInto(camera, site, site.getChildCount());
		
						for(int k = 0; k < OPTION_CAMERA.length; k++){
							option = new DefaultMutableTreeNode(OPTION_CAMERA[k]);
							treeModel.insertNodeInto(option, camera, camera.getChildCount());
						}
					}
				}
			}
			session.close();
			this.treeModel.reload();
		}
	}
	
	@Override
	public void valueChanged(TreeSelectionEvent e) {
		if(!this.buildTree){
			boolean change = false;
			Object selectedItem = ((DefaultMutableTreeNode) e.getNewLeadSelectionPath().getLastPathComponent()).getUserObject();
			//System.out.println("selected "+selectedItem.getClass());
			
			if(selectedItem instanceof String){
				Object parentItem = ((DefaultMutableTreeNode) ((DefaultMutableTreeNode)e.getNewLeadSelectionPath().getLastPathComponent()).getParent()).getUserObject();
				//System.out.println("parent "+parentItem.getClass());
				
				if(parentItem instanceof Camera){
					this.currentSite = (SiteServer)((DefaultMutableTreeNode) ((DefaultMutableTreeNode)((DefaultMutableTreeNode)e.getNewLeadSelectionPath().getLastPathComponent()).getParent()).getParent()).getUserObject();
					this.currentCamera = (Camera)parentItem;
					change = true;
				}
				else{
					this.currentSite = (SiteServer)parentItem;
					this.currentCamera = new Camera();
					change = true;
				}
			}
			else{
				this.currentSite = null;
				this.currentCamera = null;
				change = false;
			}
		
			String node = e.getNewLeadSelectionPath().getLastPathComponent().toString();
			//System.out.println(node);
			if(change){
				//System.out.println(node);
				camera_jp.setPanel(node);
			}
		}
	}
	
	public SiteServer getCurrentSite(){ return this.currentSite;	}

	public Camera getCurrentCamera(){ return this.currentCamera;	}
	
	public JTree getTree(){ return this.tree;	}
	
	public void setBuildTree(boolean build){ this.buildTree = build;	}
	
}
